﻿using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Service;
using Admin.NET.Application.Service.car_tag.Dto;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using NServiceKit;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using Org.BouncyCastle.Asn1.Pkcs;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;

namespace Admin.NET.Application;
/// <summary>
/// 标签2服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class car_tagService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<car_tag> _rep;
    public car_tagService(SqlSugarRepository<car_tag> rep)
    {
        _rep = rep;
    }

    /// <summary>
    /// 分页查询标签2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]

    public async Task<SqlSugarPagedList<car_tagOutput>> Page(car_tagInput input)
    {

        var alltagmapdata = _rep.Context.Queryable<car_tagmap>().ToList();
        var queryp = _rep.AsQueryable().Includes(m => m.subtags, t => t.taginfo).Includes(m => m.ptag)
            .Where(m => m.IsDelete == false)
               .WhereIF(input.Id > 0, m => m.Id == input.Id)
               .WhereIF(!string.IsNullOrWhiteSpace(input.title), m => m.title.Contains(input.title.Trim()))
               .WhereIF(input.type > 0, m => m.type == input.type)
               .WhereIF(input.pid > -1, m => m.pid == input.pid || m.Id== input.pid)
                .Select((m) => new car_tagOutput
                {
                   // caseCount= SqlFunc.Subqueryable<car_tagmap>().Where(tm => tm.tagid == m.Id).Count(),
                //   caseCount= alltagmapdata.Count(tm=>tm.tagid==m.Id),
                    title = m.title,
                    Id = m.Id,
                    pid = m.pid,
                    pTitle = m.ptag.title,
                    //     subtags = m.subtags,
                    zhiganList = m.subtags.Where(tg => tg.taginfo.type == (int?)car_tagType.zhigan).Select(m => m.tagid).ToList(),
                    colorList = m.subtags.Where(tg => tg.taginfo.type == (int?)car_tagType.color).Select(m => m.tagid).ToList(),
                    sexiList = m.subtags.Where(tg => tg.taginfo.type == (int?)car_tagType.sexi).Select(m => m.tagid).ToList(),
                });


            queryp = queryp.OrderBuilder(input, "pTitle");
        var list = await queryp.ToPagedListAsync(input.Page, input.PageSize);


       

        foreach (var item in list.Items)
        {
            //获取这个值的数量

            item.caseCount = alltagmapdata.Count(tm => tm.tagid == item.Id);

            //车型和系列pid如果是空的，则展示出来他本身就是pid
            if (input.type == (int)car_tagType.car || input.type == (int)car_tagType.xilie)
            {
                if (string.IsNullOrEmpty(item.pTitle))
                {
                    item.pTitle = item.title;
                    item.title = "";
                }
            }
        }
         


       return list;


    }


    /// <summary>
    ///  获取下来类型列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "car_tagPidDropdown"), HttpPost]
    public List<TreeModel> car_tagPidDropdown(car_tagInput input)
    {
        var lists = _rep.AsQueryable().Where(m=> m.IsDelete == false)
                .WhereIF(input.type > -1, u => u.type == input.type)
                   .WhereIF(input.pid > -1, u => u.pid == input.pid)
            .ToList();



        List<TreeModel> reList = new List<TreeModel>();
        foreach (var item in lists)
        {
            reList.Add(new TreeModel()
            {
                label = item.title,
                value = item.Id,
                //children = lists.Where(m => m.pid == item.Id).Select(u => new TreeModelItem
                //{
                //    label = u.carname,
                //    value = u.Id,

                //}).ToList(),
            });
        }
        return reList;
        //return await _rep.Context.Queryable<car_car>().GroupBy(m=>m.pid)
        //        .Select(u => new
        //        {
        //            Label = u.carname,
        //            Value = u.Id
        //        }
        //        ).ToListAsync();
    }


    /// <summary>
    /// 增加标签2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task Add(Addcar_tagInput input)
    {
        var entity = input.Adapt<car_tag>();
        if (string.IsNullOrEmpty(entity.title))
        {
            throw Oops.Oh(ErrorCodeEnum.D0007);
        }
        await _rep.InsertAsync(entity);
    }

    /// <summary>
    /// 删除标签2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(Deletecar_tagInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);

        if (_rep.Count(m => m.pid == entity.Id) > 0)
        {
            throw Oops.Oh(ErrorCodeEnum.D1007);
        }

        if (_rep.Context.Queryable<car_tagmap>().Count(m => m.tagid == entity.Id) > 0)
        {
            throw Oops.Oh(ErrorCodeEnum.D1007);
        }

        await _rep.FakeDeleteAsync(entity);   //假删除
    }

    /// <summary>
    /// 更新标签2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [AllowAnonymous]
    public async Task Update(Updatecar_tagInput input)
    {
        var entity = input.Adapt<car_tag>();
        #region  bug 更新tag表，pid会被覆盖
        //25.5.15更新  bug 更新tag表，pid会被覆盖
        //if (input.type == 3 && input.pid!=0)
        //{
        //   // //先把之前的设置为0 ，
        //   // _rep.Context.Updateable<car_tag>().SetColumns(m => m.pid == 0).Where(m => m.pid == input.Id).AddQueue();
        //   // var upcout = _rep.Context.SaveQueues();
        //   // if (input.colorList != null)
        //   // {
        //   //     foreach (var item in input.colorList)
        //   //     {
        //   //         _rep.Context.Updateable<car_tag>().SetColumns(m => m.pid == input.Id).Where(m => m.Id == item).AddQueue();
        //   //     }

        //   // }
        //   // if (input.sexiList != null)
        //   // {
        //   //     foreach (var item in input.sexiList)
        //   //     {
        //   //         _rep.Context.Updateable<car_tag>().SetColumns(m => m.pid == input.Id).Where(m => m.Id == item).AddQueue();
        //   //     }
        //   // }
        //   // if (input.zhiganList != null)
        //   // {
        //   //     foreach (var item in input.zhiganList)
        //   //     {
        //   //         _rep.Context.Updateable<car_tag>().SetColumns(m => m.pid == input.Id).Where(m => m.Id == item).AddQueue();
        //   //     }
        //   // }
        //   //upcout=   _rep.Context.SaveQueues();


        //}
        #endregion


       //25.7.10 更新  用cat_subtag表存储
        if (input.type == 3 && input.pid != 0)
        {
            //先把之前的删除，
            _rep.Context.Deleteable<car_tagSub>().Where(m => m.pid == input.Id).AddQueue();
          //  var decout = _rep.Context.SaveQueues();
            if (input.colorList != null)
            {
                foreach (var item in input.colorList)
                {
                    _rep.Context.Insertable(new car_tagSub()
                    {
                        pid= input.Id,
                         tagid= item,
                         type=(int?) car_tagType.color
                    }).AddQueue();
                }
            }
            if (input.sexiList != null)
            {
                foreach (var item in input.sexiList)
                {
                    _rep.Context.Insertable(new car_tagSub()
                    {
                        pid = input.Id,
                        tagid = item,
                        type = (int?)car_tagType.sexi
                    }).AddQueue();
                }
            }
            if (input.zhiganList != null)
            {
                foreach (var item in input.zhiganList)
                {
                    _rep.Context.Insertable(new car_tagSub()
                    {
                        pid = input.Id,
                        tagid = item,
                        type = (int?)car_tagType.zhigan
                    }).AddQueue();
                }
            }
            var addcout = _rep.Context.SaveQueues();


        }
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取标签2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    //[HttpGet]
    //[ApiDescriptionSettings(Name = "Detail")]
    //public async Task<car_tag> Get([FromQuery] QueryByIdcar_tagInput input)
    //{
    //}

    /// <summary>
    /// 获取标签2列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<car_tagOutput>> List([FromQuery] car_tagInput input)
    {
        return await _rep.AsQueryable().Select<car_tagOutput>().ToListAsync();
    }





}

